package link.hwx.controller.oa;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import link.hwx.entity.oa.*;
import link.hwx.service.oa.OaInfoService;
import link.hwx.service.oa.OaPurchaseOrderService;
import link.hwx.service.u9.PurchaseOrderService;
import link.hwx.util.AjaxResult;
import link.hwx.util.CommonSetData;
import link.hwx.util.HttpManager;
import link.hwx.util.IdentityVerifyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Oa采购单接口
 */
@RestController
@RequestMapping("/cx/oa")
public class OaPurchaseOrderOpenApi {

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private OaPurchaseOrderService oaPurchaseOrderService;
    @Autowired
    private OaInfoService oaInfoService;


    @GetMapping("/oaCreatePurchaseOrder")
    public AjaxResult oaCreatePr(@RequestParam Map<String, Object> data) {
        //创建人
        String docNo = String.valueOf(data.get("docNo"));
        String srmUserId = String.valueOf(data.get("userId"));
        if ("".equals(docNo) || docNo == null || "null".equals(docNo)) {
            return AjaxResult.error("单据编号不能为空");
        }

        if ("".equals(srmUserId) ||srmUserId == null || "null".equals(srmUserId)) {
            return AjaxResult.error("用户id不能为空");
        }
        if(oaPurchaseOrderService.findPurchaseOrderByDocnoType(CommonSetData.oaPurchaseOrderTableMainDbNameD,docNo, "0").size()>0){
            return AjaxResult.error("已提交单据到OA");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        AjaxResult resData = createRequest(sdf.format(new Date()), srmUserId, docNo);
       /*if ("200".equals(resData.get("code").toString())) {
            purchaseOrderService.updateDescFlexFieldPub2ByDocNo("提交OA", docNo);
        }*/
        return resData;
    }

    /**
     * oa单据退回
     *
     * @param data
     * @return
     */
//    @PostMapping("/oaRejPurchaseOrder")
//    public AjaxResult rejPurchaseOrder(@RequestBody Map<String, Object> data) {
//        String requestId = (String) data.get("requestId");
//        OaBillInfoVo oaPoInfo = oaPurchaseOrderService.findPurchaseOrderByRequestId(CommonSetData.oaPurchaseOrderTableMainDbNameD, requestId);
//        //有u9单据号退回删除
//        if (oaPoInfo != null) {
//            //如果是u9提交，删除oa请款单，u9修改状态
//            if (StringUtils.isNotEmpty(oaPoInfo.getSrmDocNo())) {
//                //if (rejRequest(data) != null) {
//                System.out.println(oaPoInfo.getSrmDocNo());
//                purchaseOrderService.updateDescFlexFieldPub2ByDocNo("OA退回", oaPoInfo.getSrmDocNo());
//                purchaseOrderService.updatePoStatusByDocNo("0", oaPoInfo.getSrmDocNo());
//                Map<String, Object> poInfoMap = purchaseOrderService.findPurchaseOrderByDocNo(oaPoInfo.getSrmDocNo());
//                purchaseOrderService.updatePoLineStatusByPoId("0",poInfoMap.get("id").toString());
//                purchaseOrderService.updatePoShipLineStatusByPoId("0",poInfoMap.get("id").toString());
//                return AjaxResult.success();
//                // }
//            } else {
//                return AjaxResult.success();
//            }
//        }
//        return AjaxResult.error();
//    }


    /**
     * 判断是否是退回之后提交
     *
     * @param data
     * @return
     */
    @PostMapping("/oaRejSubPurchaseOrder")
    public AjaxResult oaRejSubPr(@RequestBody Map<String, Object> data) {
        String requestId = (String) data.get("requestId");
        OaBillInfoVo oaPayReqInfo = oaPurchaseOrderService.findPurchaseOrderByRequestId(CommonSetData.oaPurchaseOrderTableMainDbNameD, requestId);
        //有u9单据号退回删除
        if (oaPayReqInfo != null) {
            //如果是u9提交，u9修改状态
            System.out.println("该单据为srm创建:" + oaPayReqInfo.getSrmDocNo());
            if (StringUtils.isNotEmpty(oaPayReqInfo.getSrmDocNo())) {
                return AjaxResult.error("该单据为srm创建,不能提交已退回单据");
                // }
            } else {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error();
    }

    /**
     * 创建流程入口
     *
     * @param requestnamesuffix
     * @param srmUserid
     */
    public AjaxResult createRequest(String requestnamesuffix, String srmUserid, String docNo) {

        IdentityVerifyUtil identityVerifyUtil = IdentityVerifyUtil.getInstance();
        String spk = identityVerifyUtil.getSPK();
        String secret = identityVerifyUtil.getSECRET();
        String token = identityVerifyUtil.getToken();
        if (spk == null || secret == null || token == null) {
            return null;
        }
       // BaseVo u9UserInfo = baseInfoService.findUserById(srmUserid);
        //获取Oa信息
      //  String userCode = u9UserInfo.getCode();//oa和u9编号相同
//        OaUserInfo oaUserInfo = oaInfoService.findUserInfoByCode(userCode);
        OaUserInfo oaUserInfo = oaInfoService.findUserInfoById(srmUserid);
        if (oaUserInfo == null) {
            return AjaxResult.error("OA没有该用户");
        }
        String userid = oaUserInfo.getId();
        //OaUserInfo oaUserInfo = new OaUserInfo();
        //获取u9采购头数据
        List<Map<String, String>> headcol = purchaseOrderService.selectColumnsHead();
        Map<String, String> headData = purchaseOrderService.selectPoHeadById(docNo);
        //获取行数据
        List<Map<String, String>> linecol = purchaseOrderService.selectColumnsLine();
        List<Map<String, String>> lineData = purchaseOrderService.selectPoLineById(docNo);
        //
        String url = IdentityVerifyUtil.HOST + "/api/workflow/paService/doCreateRequest";
        HttpManager http = new HttpManager();
        Map<String, String> heads = IdentityVerifyUtil.getHttpHeads(token, srmUserid, spk);
        Map<String, String> params = new HashMap<>();
        params.put("requestName", "采购单" + requestnamesuffix + " srm导入" + docNo);
        params.put("mainData", getFormMainData(headData, headcol, oaUserInfo));
        params.put("detailData", getFormDetailData(lineData, linecol));
        params.put("workflowId", CommonSetData.oaPurchaseOrderWorkflowid);
        params.put("remark", "采购单创建");
        try {
            http.cookieStore.clear();
            String res = http.postDataSSL(url, params, heads);
            if (res != null) {
                JSONObject resJson = JSONObject.parseObject(res);
                String code = String.valueOf(resJson.get("code"));

                if ("SUCCESS".equals(code)) {
                    JSONObject resdata = resJson.getJSONObject("data");
                    //填入srm单据编号S
                    oaPurchaseOrderService.updatePurchaseOrderSrmDocNoByRequestId(CommonSetData.oaPurchaseOrderTableMainDbNameD, resdata.getString("requestid"), docNo);
                    OaBillInfoVo oninfo = oaPurchaseOrderService.findPurchaseOrderByRequestId(CommonSetData.oaPurchaseOrderTableMainDbNameD, resdata.getString("requestid"));
                    return AjaxResult.success("操作成功",oninfo.getOaDocNo());

                } else {
                    return AjaxResult.error(resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString(), resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString());
                }
            }
            return AjaxResult.error(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 主表数据
     * <p>
     * 附件上传 包含base64, http等
     * 包含浏览框数据，单行文本数据
     *
     * @return
     */
    private String getFormMainData(Map<String, String> headData, List<Map<String, String>> headcol, OaUserInfo oaUserInfo) {
        List<WorkflowRequestTableField> mainData = new ArrayList<>();

   /*     if (oaUserInfo != null) {
            //申请人  根据code查出来赋值
            WorkflowRequestTableField sqr = new WorkflowRequestTableField();
            sqr.setFieldName("sqr");
            sqr.setFieldValue(oaUserInfo.getId());
            mainData.add(sqr);
            //申请部门
            WorkflowRequestTableField sqbm = new WorkflowRequestTableField();
            sqbm.setFieldName("sqbm");
            sqbm.setFieldValue(oaUserInfo.getDepartmentid());
            mainData.add(sqbm);
            //公司
            WorkflowRequestTableField gs = new WorkflowRequestTableField();
            gs.setFieldName("gs");
            gs.setFieldValue(oaUserInfo.getSubcompanyid1());
            mainData.add(gs);
        }*/
       /* SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        WorkflowRequestTableField sqrq = new WorkflowRequestTableField();
        sqrq.setFieldName("sqrq");
        sqrq.setFieldValue(sf.format(new Date()));
        mainData.add(sqrq);*/

        for (int j = 0; j < headcol.size(); j++) {
            String colName = headcol.get(j).get("name");

            if (!"docNo".equals(colName)) {
                WorkflowRequestTableField col = new WorkflowRequestTableField();
                col.setFieldName(colName);
                col.setFieldValue(headData.get(colName));
                mainData.add(col);
            }

        }
        return JSONObject.toJSONString(mainData);
    }

    /**
     * 明细数据
     *
     * @return
     */
    private String getFormDetailData(List<Map<String, String>> lineData, List<Map<String, String>> lineCol) {
        List<WorkflowDetailTableInfoEntity> details = new ArrayList<>();

        //明细信息
        WorkflowDetailTableInfoEntity detail1 = new WorkflowDetailTableInfoEntity();
        detail1.setTableDBName(CommonSetData.oaPurchaseOrderTableDbNameD);
        //明细数据
        List<WorkflowRequestTableRecord> detailRows = new ArrayList<WorkflowRequestTableRecord>();
        //明细行数据
        for (int i = 0; i < lineData.size(); i++) {
            WorkflowRequestTableRecord row1 = new WorkflowRequestTableRecord();
            List<WorkflowRequestTableField> rowDatas = new ArrayList<>();
            for (int j = 0; j < lineCol.size(); j++) {
                String colName = lineCol.get(j).get("name");
                if (!"docNo".equals(colName)) {
                    if ("cpurorderid".equals(colName)) {
                        if (StringUtils.isNotEmpty(lineData.get(i).get(colName))) {
                            JSONObject user = new JSONObject();
                            user.put("usercode", "admin");
                            user.put("userpwd", "d41d8cd98f00b204e9800998ecf8427e");
                            JSONObject voucher = new JSONObject();
                            voucher.put("voucherno", "focus_srm_purchaseorder");
                            JSONObject datatable = new JSONObject();
                            datatable.put("user", user);
                            datatable.put("voucher", voucher);
                            datatable.put("KeyID", lineData.get(i).get(colName));
                            String data = JSON.toJSONString(datatable);
                            String srmUrl = CommonSetData.serveSrmIp + "/sysplat/dataget/data.ashx?type=webapi&optype=getvoucherfiles";
                            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                            ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
                            builder.addTextBody("data", data, contentType);
                            String result = HttpManager.sendPostFormData(srmUrl, builder,data);
                            if (StringUtils.isNotEmpty(result)) {
                                JSONObject resultmap = JSON.parseObject(result);
                                if (resultmap.getBoolean("Success")) {
                                    List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
                                    List<Map<String, Object>> resultfile = (List<Map<String, Object>>) resultmap.get("Result");
                                    for (int g = 0; g < resultfile.size(); g++) {
                                        String filestr = String.valueOf(resultfile.get(g).get("File")).replaceAll("\r\n", "");
                                        Map<String, String> filemap = new HashMap<String, String>();
                                        filemap.put("fileName", String.valueOf(resultfile.get(g).get("Title")));
                                        filemap.put("filePath", "base64:" + filestr);
                                        fileList.add(filemap);
                                    }


                                    String filestrs = JSONObject.toJSONString(fileList);
                                    WorkflowRequestTableField col = new WorkflowRequestTableField();
                                    col.setFieldName("xgfj");
                                    col.setFieldValue(filestrs);
                                    rowDatas.add(col);
                                    WorkflowRequestTableField col1 = new WorkflowRequestTableField();
                                    col1.setFieldName(colName);
                                    col1.setFieldValue(lineData.get(i).get(colName));
                                    rowDatas.add(col1);
                                }
                            }
                        }
                    }else {
                        WorkflowRequestTableField col = new WorkflowRequestTableField();
                        col.setFieldName(colName);
                        col.setFieldValue(lineData.get(i).get(colName));
                        rowDatas.add(col);
                    }
                }
            }
            row1.setRecordOrder(0);
            row1.setWorkflowRequestTableFields(rowDatas);
            detailRows.add(row1);

        }
        detail1.setWorkflowRequestTableRecords(detailRows);

        details.add(detail1);
        return JSONObject.toJSONString(details);

    }
    @PostMapping("/oaDelPurchaseOrder")
    public AjaxResult delPurchaseOrder(@RequestBody Map<String, Object> jsonStr){
        if (jsonStr == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            return AjaxResult.error("数据不能为空!");
        }

        //通过requestid获取oa单据
        String oalcid = String.valueOf(jsonStr.get("lcid"));
        if (StringUtils.isNotEmpty(oalcid)) {
            String requestId = (String) jsonStr.get("requestId");
            IdentityVerifyUtil identityVerifyUtil = IdentityVerifyUtil.getInstance();
            String spk = identityVerifyUtil.getSPK();
            String secret = identityVerifyUtil.getSECRET();
            String token = identityVerifyUtil.getToken();
            if (spk == null || secret == null || token == null) {
                return null;
            }
            String url = IdentityVerifyUtil.HOST + "/api/workflow/paService/deleteRequest";
            HttpManager http = new HttpManager();
            Map<String, Object> currentUser = (Map<String, Object>) jsonStr.get("currentUser");
            String apprid = (String) jsonStr.get("cjr");//zhidanren
            Map<String, String> heads = IdentityVerifyUtil.getHttpHeads(token, apprid, spk);
            Map<String, String> params = new HashMap<>();
            params.put("requestId", requestId);
            params.put("ismonitor", "1");
            http.cookieStore.clear();
            try {
                String res = http.postDataSSL(url, params, heads);
                if (res != null) {
                    JSONObject resJson = JSONObject.parseObject(res);
                    String code = String.valueOf(resJson.get("code"));

                    if ("SUCCESS".equals(code)) {
                        //填入srm单据编号S
                        return AjaxResult.success();

                    } else {
                        return AjaxResult.error(resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString(), resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString());
                    }
                }
                return AjaxResult.error(res);
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }else {
            return AjaxResult.error();
        }
        return null;
    }
}
